package util

import java.util.Collections
import scala.math._

/**
 * <p>
 * Created by IntelliJ IDEA.
 * User: zslajchrt
 * Date: Oct 18, 2010
 * Time: 12:32:10 PM
 */

object ColUtils {

  /**
   * Moves the element located by the locator in the given list about delta steps.
   */
  def moveInList[X](list: List[X], delta: Int, locator: (X) => Boolean): List[X] = {
    if (delta == 0) {
      list
    } else {
      val index = list.findIndexOf(locator)
      require(index >= 0, "Element not found")
      require(index + delta < list.size, "Moving beyound the limit of the list [" + (index + delta) + "/" + list.size + "]")
      require(index + delta >= 0, "Moving beyound the limit of the list [" + (index + delta) + "/" + list.size + "]")

      val (part1, part2) = if (delta > 0) {
        // (a,b,)((X,c,)(Y,d))
        // (a,b,)((Y,c,)(X,d))
        list.splitAt(index)
      } else {
        // (a,b,)((Y,c,)(X,d))
        // (a,b,)((X,c,)(Y,d))
        list.splitAt(index + delta)
      }

      val (part2a, part2b) = part2.splitAt(abs(delta))
      part1 ::: (part2b.head :: part2a.tail) ::: (part2a.head :: part2b.tail)
    }
  }

  class JavaEnumeration[T](val enumer: java.util.Enumeration[T]) {
    def asScalaList(): List[T] = {
      var list: List[T] = List()
      while (enumer.hasMoreElements) {
        val e = enumer.nextElement
        list = e :: list
      }
      list.reverse
    }
  }

  class ScalaList[T](val scalaList: List[T]) {
    def asJavaEnumeration(): java.util.Enumeration[T] = {
      val arrayList = new java.util.ArrayList[T]()
      scalaList.foreach(arrayList.add(_))
      Collections.enumeration[T](arrayList)
    }
  }

  implicit def convertFromJavaEnumeration[T](enumer: java.util.Enumeration[T]): JavaEnumeration[T] =
    new JavaEnumeration[T](enumer)

  implicit def convertFromScalaList[T](scalaList: List[T]): ScalaList[T] =
    new ScalaList[T](scalaList)

  implicit def convertJavaListToScalaList[T](javaList: java.util.List[T]): List[T] =
    List[T](javaList.toArray.asInstanceOf[Array[T]]: _*)

  implicit def convertJavaSetToScalaList[T](javaList: java.util.Set[T]): List[T] =
    List[T](javaList.toArray.asInstanceOf[Array[T]]: _*)
}

